package br.com.inner.dao;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;

import br.com.inner.custom.CustomException;
import br.com.inner.custom.JPAManager;
import br.com.inner.modelo.Empresa;
import br.com.inner.modelo.Usuario;

public class EmpresaDBDao implements EmpresaDao{

	public List<Empresa> pesquisaEmpresa(String nmFantasia, String uf, String cidade) throws CustomException {
		EntityManager em = JPAManager.getEntityManager();
		/*JPAManager.beginTransaction();
		Query q = em.createNamedQuery("Empresas");
		q.setParameter("nmFantasia", nmFantasia);
		return q.getResultList();
    	em.clear();
    	JPAManager.beginTransaction();*/
    	String sql = "SELECT e FROM Empresa e WHERE e.nomeFantasia like '"+nmFantasia+"'";
    	if(!uf.equalsIgnoreCase("-1")){
    		sql += " and e.uf.cdUf = "+uf+"";
    	}
    	if(StringUtils.isNotBlank(cidade)){
    		sql += " and e.cidade like '"+cidade+"'";
    	}
    	Query q = em.createQuery(sql);
		//JPAManager.commitTransaction();
		return q.getResultList();
	}
	
	public Empresa getEmpresa(BigDecimal cdUsuario) throws CustomException {
		EntityManager em = JPAManager.getEntityManager();
		Usuario usu = (Usuario)em.find(Usuario.class, cdUsuario);
		System.out.println("Fez o find no Usuario, retornou: "+usu.getCdUsuario()+" - "+usu.getNmUsuario());
		return (Empresa)em.find(Empresa.class, usu.getEmpresa().getCdEmpresa());
	}
	
	public void update(Empresa empresa){
		try {
			EntityManager em = JPAManager.getEntityManager();
			em.clear();
			JPAManager.beginTransaction();
			em.merge(empresa);
			JPAManager.commitTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			JPAManager.rollbackTransaction();
			e.printStackTrace();
		}
	}

}
